package tw.cating.karmasaver.plurk;

import java.io.IOException;
import java.util.Calendar;

import tw.cating.karmasaver.Constants;
import tw.cating.karmasaver.R;
import tw.cating.karmasaver.intef.dataChangedListener;
import tw.cating.karmasaver.intef.finishListener;
import tw.cating.karmasaver.rss.rssAdapter;
import tw.cating.karmasaver.rss.structer.rssNode;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class autoPlurkActivity extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.getInstance(this);
        mContext = this;
		Calendar c = Calendar.getInstance();
		Log.i("Cating", "saveKarma " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE));
		plurk = new plurkApi(mContext);
		if (plurk.isLogined() == false) {
			prepareLogin();
		} else {
			mHandler.sendEmptyMessage(MSG_LOGINSUCCESSED);
		}
		setContentView(R.layout.autoplurk);
    }
    
	public static final int MSG_ABORT = -1;
	public static final int MSG_PREPARELOGININFOSUCCESSED = 1;
	public static final int MSG_LOGINSUCCESSED = 2;
	public static final int MSG_FINISH = 3;
	protected Handler mHandler = new Handler () {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_PREPARELOGININFOSUCCESSED:
				Log.i("Cating", "MSG_PREPARELOGININFOSUCCESSED");
				LoginInfoReady();
				break;
			case MSG_LOGINSUCCESSED:
				Log.i("Cating", "MSG_LOGINSUCCESSED");
				LoginSuccessed();
				break;
			case MSG_FINISH:
				Log.i("Cating", "MSG_FINISH");
				finish();
				break;
			case MSG_ABORT:
				Log.i("Cating", "MSG_ABORT");
				finish();
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	protected String mUsername = "";
	protected String mPassword = "";
	protected rssAdapter mAdapter = null;
	plurkApi plurk = null;
	Context mContext = null;
	
	protected void LoginSuccessed() {
		mAdapter = new rssAdapter(mContext, new dataChangedListener() {
			public void onDataChanged() {
				// TODO Auto-generated method stub
				if (mAdapter.getCount() > 0) {
					rssNode node = (rssNode)mAdapter.getItem(0);
					String msg = node.getShorternLink() + " (" + node.getDescription() + ")";
					plurk.requestPrivatePost(msg, new finishListener() {
						
						public void onFinish(int result) {
							// TODO Auto-generated method stub
							if (result == plurkApi.POSTRESULT_SUCCESSED) {
								mHandler.sendEmptyMessage(MSG_FINISH);
							} else {
								mHandler.sendEmptyMessage(MSG_ABORT);
							}
						}
					});
				} else {
					mHandler.sendEmptyMessage(MSG_ABORT);
				}	
			}
		});
	}
	
	protected void LoginInfoReady() {
        plurk.requestLogin(mUsername, mPassword, new finishListener() {

			public void onFinish(int result) {
				// TODO Auto-generated method stub
				if (result == plurkApi.LOGINRESULT_SUCCESSED)
					mHandler.sendEmptyMessage(MSG_LOGINSUCCESSED);
				else
					mHandler.sendEmptyMessage(MSG_ABORT);
			}
        	
        });	
	}
	
	protected void prepareLogin() {
		final AccountManager am = AccountManager.get(mContext);
        final Account[] accs = am.getAccountsByType(Constants.ACCOUNT_TYPE);
        
        if (accs.length >= 0) {
    		final Runnable run = new Runnable() {

    			public void run() {
    				// TODO Auto-generated method stub
    	        	Account acc = accs[0];
    	        	mUsername = acc.name;
    	        	AccountManagerFuture<Bundle> accountManagerFuture
    	            = am.getAuthToken(acc, Constants.AUTHTOKEN_TYPE, null, (Activity)mContext, null, null);
    	        	try {
    					Bundle authTokenBundle = accountManagerFuture.getResult();
    					mPassword = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
    					mHandler.sendEmptyMessage(MSG_PREPARELOGININFOSUCCESSED);
    				} catch (OperationCanceledException e) {
    					// TODO Auto-generated catch block
    					mHandler.sendEmptyMessage(MSG_ABORT);
    					e.printStackTrace();
    				} catch (AuthenticatorException e) {
    					// TODO Auto-generated catch block
    					mHandler.sendEmptyMessage(MSG_ABORT);
    					e.printStackTrace();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					mHandler.sendEmptyMessage(MSG_ABORT);
    					e.printStackTrace();
    				}				
    			}
    		};
    		
            final Thread t = new Thread() {
                @Override
                public void run() {
                    try {
                        run.run();
                    } finally {

                    }
                }
            };
            t.start();
        } else {
        	mHandler.sendEmptyMessage(MSG_ABORT);
        }
	}
}
